<template>
    <div class="login-container">
      <h2>登录</h2>
      <form @submit.prevent="handleLogin">
        <div class="form-group">
          <label for="username">用户名:</label>
          <input type="text" id="username" v-model="username" required />
        </div>
        <div class="form-group">
          <label for="password">密码:</label>
          <input type="password" id="password" v-model="password" required />
        </div>
        <button type="submit">登录</button>
      </form>
      <div class="links">
        <a href="/register">注册</a>
        <a href="/forgot">忘记密码</a>
        <button @click="handleAdminLogin">管理员登录</button>
      </div>
    </div>
</template>
  
  <script setup>
  import { ref, onBeforeMount } from 'vue';
  import axios from 'axios';
  import { useRouter } from 'vue-router';
  
  const router = useRouter();
  const username = ref('');
  const password = ref('');
  
  // 设置token到localStorage
  function setAuthToken(token, tokenHead) {
    axios.defaults.headers.common['Authorization'] = `${tokenHead} ${token}`;
    localStorage.setItem('authToken', token);
    localStorage.setItem('Bearer', tokenHead);
  }
  
  // 检查localStorage中的token并自动登录
  function autoLogin() {
    const token = localStorage.getItem('authToken');
    const tokenHead = localStorage.getItem('Bearer');
    if (token && tokenHead) {
      router.push({ name: 'home' });
    }
  }
  
  // axios响应拦截器
  axios.interceptors.response.use(
    response => {
      if (response.data && response.data.code === 500 && response.data.message === "未登录") {
        localStorage.removeItem('authToken');
        localStorage.removeItem('Bearer');
        router.push({ name: 'login' });
      }
      return response;
    },
    error => {
      if (error.response) {
        // 可以在这里处理特定的错误情况
      }
      return Promise.reject(error);
    }
  );
  
  // 在组件挂载前调用autoLogin
  onBeforeMount(autoLogin);
  
  const handleLogin = async () => {
    try {
      const response = await axios.post('http://8.219.49.219:8080/onlineShopping/user/login', {
        username: username.value,
        password: password.value
      }, {
        withCredentials: true
      });
      if (response.data.code === 200) {
        if (response.data.data.state) {
          const token = response.data.data.token;
          const tokenHead = response.data.data.tokenHead;
          setAuthToken(token, tokenHead);
          router.push({ name: 'home' });
        } else {
          console.error('Login failed:', response.data.message);
        }
      } else {
        console.error('Error:', response.data.message);
        alert('用户名或密码错误');
      }
    } catch (error) {
      console.error('Error during login:', error);
    }
  };
  
  const handleAdminLogin = async () => {
    try {
      const response = await axios.post('http://8.219.49.219:8080/onlineShopping/admin/login', {
        username: username.value,
        password: password.value
      }, {
        withCredentials: true
      });
      if (response.data.code === 200) {
        if (response.data.data.state) {
          const token = response.data.data.token;
          const tokenHead = response.data.data.tokenHead;
          setAuthToken(token, tokenHead);
          router.push({ name: 'adminDashboard' }); // 假设管理员登录后跳转到adminDashboard页面
        } else {
          console.error('Admin Login failed:', response.data.message);
        }
      } else {
        console.error('Error:', response.data.message);
        alert('管理员用户名或密码错误');
      }
    } catch (error) {
      console.error('Error during admin login:', error);
    }
  };
  </script>
  
  <style scoped>
  .login-container {
    max-width: 400px;
    margin: 50px auto;
    padding: 20px;
    border-radius: 8px;
    background-color: rgba(255, 255, 255, 0.8); 
    box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
    text-align: center;
    color: #333; 
    background-image: url('C:\Users\laisir\Desktop\231\online\onlineshopping\public\pictures\bg.jpg'); 
    background-size: cover; 
    background-position: center; 
    background-blend-mode: multiply; 
  }
  
  .login-container h2 {
    margin-bottom: 20px;
    font-size: 24px;
    color: #333;
    font-family: 'Roboto', sans-serif; 
  }
  
  .form-group {
    margin-bottom: 20px;
    text-align: left;
  }
  
  .form-group label {
    display: block;
    margin-bottom: 5px;
    font-size: 16px;
    color: #666;
  }
  
  .form-group input {
    width: 100%;
    padding: 10px;
    border: 1px solid #ccc;
    border-radius: 4px;
    font-size: 16px;
    background-color: #f8f8f8; 
    color: #333; 
    box-sizing: border-box;
  }
  
  button {
    width: 100%;
    padding: 12px;
    background-color: #4CAF50; 
    color: white;
    border: none;
    border-radius: 4px;
    cursor: pointer;
    font-size: 18px;
    transition: background-color 0.3s ease;
  }
  
  button:hover {
    background-color: #45a049; 
  }
  
  .links {
    margin-top: 20px;
    text-align: center;
  }
  
  .links a {
    margin: 0 10px;
    color: #4CAF50; 
    text-decoration: none;
    font-size: 16px;
  }
  
  .links a:hover {
    text-decoration: underline;
  }
  
  .links button {
    margin: 0 10px;
    padding: 10px 20px;
    background-color: #007BFF; 
    color: white;
    border: none;
    border-radius: 4px;
    cursor: pointer;
    font-size: 16px;
    transition: background-color 0.3s ease;
  }
  
  .links button:hover {
    background-color: #0056b3; 
  }
  </style>
  